import invokeTable from './invokeTable.js'
import invokeSearch from './invokeSearch.js'
import SearchHeader from '@components/table/SearchHeader'
import MultiFunTable from '@components/table/MultiFunTable'
import TablePagination from '@components/table/TablePagination'
import { deepCopyObjArray } from '../../assets/js/help.js';

export default {
  mixins: [invokeTable, invokeSearch],
  components: {
    SearchHeader,
    MultiFunTable,
    TablePagination
  },
  data () {
    return {
      searchParams: {},
      pageNumber: 1,
      pageSize: 20,
      columnName: '', //把列名经过处理转成数据库需要的格式
      sortType: '',
      notFormatColumn: '',
      selectionList: '',
      otherParams: {},
      areaTreeData:[], //区域树数据
      channelTreeData:[], //通道树数据
      curPagePath:'', //现在的页面路由
      userLoginId: '', //当前用户登录id
      reloadChannelTree:false, //重建通道树
      reloadAreaTree:false, //重建区域树
      isNeedAreaTree:true, //是否需要区域树
      isNeedChannelTree:true, //是否需要通道树
    }
  },
  watch : {
    notFormatColumn: function (val) {
      this.columnName = this.handleOrderBy(val);
    }
  },
  created () {
    this.getSortObj();
    this.userLoginId = window.sessionStorage.getItem('loginid')
    this.curPagePath = this.userLoginId+'-'+this.$route.path
  },
  methods: {
    confirmSearch(params) {
      let parkIdStr = this.paramName
      let arr = Object.keys(this.otherParams)
      if(parkIdStr){ //是否需要停车场树
        if(!arr.length || !this.otherParams.hasOwnProperty(parkIdStr) || !this.otherParams[parkIdStr]){
          this.showToast('请先选择一个停车场',0,1500);
          return;
        }
      }
      this.pageNumber = 1;
      this.getList();
    },

    getSortObj () {
      let _name = this.$route.meta.name;
      let info = localStorage.getItem(_name);
      info = info ? JSON.parse(info) : {};
      if(info && info.sort) {
        let sortObj = info.sort;
        let _orderTy = sortObj.orderTy;
        this.notFormatColumn = sortObj.orderBy;
        this.sortType = _orderTy == '' ? '' : (_orderTy == 'ascending' ? 'ASC' : 'DESC');
        this.columnName = this.handleOrderBy(sortObj.orderBy);
      }
    },
    //将排序的字段名称(驼峰式)转为后台数据库所需要的格式（下划线分隔式）
    // eg. parkingSpaceNumber 转为 parking_space_number
    handleOrderBy (prop) {
      if(prop) {
        if('Str' === prop.substr(-3)) {
          prop = prop.substring(0, prop.length - 3);
        }
        return prop.split('').map(x => {
          return x >= 'A' && x <='Z' ? '_' + x.toLowerCase() : x;
        }).reduce((x, y) => {
          return x + y;
        })
      }
      return '';
    },
    // 获取当前的页数和每页的数据数
    getPagination (curPage, pageSize) {
      this.pageNumber = curPage;
      this.pageSize = pageSize ? pageSize : this.pageSize;
      this.getList();
    },
    getNextPage (flag) {
      let pages = Math.ceil(this.total / this.pageSize);
      switch(flag) {
        case '+':
          if(this.pageNumber >= pages) {
            this.showToast('当前已经是最后一页！', 2, 1500);
            return;
          } else {
            this.pageNumber++;
          }
          break;
        case '-':
          if(this.pageNumber <= 1) {
            this.showToast('当前已经是第一页！', 2, 1500);
            return;
          } else {
            this.pageNumber--;
          }
          break;
        default: break;
      }
      this.getList();
    },

    setSelectedNode (params) {
      let _paramName = this.paramName ? this.paramName : 'parkId';
      if(params) {
        if(params['parkIds']) {
          let obj = {};
          obj[_paramName] = params['parkIds'];
          this.otherParams = $.extend({}, this.otherParams, obj);
          // 将所选的停车场id放到session-start
          let curPageCache = window.localStorage.getItem(this.curPagePath)
          let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
          _curPageCache.parkIds = params['parkIds']
          _curPageCache.parkNames = params['name']
          _curPageCache.parkSysType = params['parkSysType']
          window.localStorage.setItem(this.curPagePath,JSON.stringify(_curPageCache))
          // 将所选的停车场id放到session-end
        } else {
          delete this.otherParams[_paramName];
          window.localStorage.removeItem(this.curPagePath)
        }
      }
    },
    // 选择停车场节点
    selectParkingLotNode2(params){ 
      let self = this
      let _paramName = this.paramName ? this.paramName : 'parkId';
      if(params){
        let searchObj = {}
        searchObj[_paramName] = params['parkIds'] ? params['parkIds'] : ''
        searchObj['parkSysType'] = params[_paramName] ? params['parkSysType'] : ''
        this.otherParams = $.extend({}, this.otherParams, searchObj);
        let curPageCache = window.localStorage.getItem(self.curPagePath)
        let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
        if(params['parkIds']){
          let obj = {}
          obj['parkIds'] = params['parkIds'];
          _curPageCache.parkIds = params['parkIds']
          _curPageCache.parkNames = params['name']
          _curPageCache.parkSysType = params['parkSysType']
          if(params['parkSysType']===0){ //vems
            self.isNeedAreaTree = false
            self.isNeedChannelTree = false
          }else{
            self.isNeedAreaTree = true
            self.isNeedChannelTree = true
          }
          if(params['parkSysType']==1){ //智泊云停车场
            // 加载该停车场全部区域的通道数据
            self.getAreaAllChannelData(obj)
            // 加载停车场区域数据
            self.getAreaData(obj)
          }
          window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
        }else{
          self.isNeedAreaTree = true
          self.isNeedChannelTree = true
          window.localStorage.removeItem(self.curPagePath)
          this.reloadAreaTree = !this.reloadAreaTree
          this.reloadChannelTree = !this.reloadChannelTree
        }
      }
    },
    // 选择停车场节点
    selectParkingLotNode(params){ 
      let self = this
      let _paramName = this.paramName ? this.paramName : 'parkId';
      if(params){
        let searchObj = {}
        searchObj[_paramName] = params['parkIds'] ? params['parkIds'] : ''
        searchObj['parkSysType'] = params[_paramName] ? params['parkSysType'] : ''
        this.otherParams = $.extend({}, this.otherParams, searchObj);
        let curPageCache = window.localStorage.getItem(self.curPagePath)
        let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
        if(params['parkIds']){
          let obj = {}
          obj['parkIds'] = params['parkIds'];
          _curPageCache.parkIds = params['parkIds']
          _curPageCache.parkNames = params['name']
          _curPageCache.parkSysType = params['parkSysType']
          if(params['parkSysType']===0){ //vems
            self.isNeedAreaTree = false
            self.isNeedChannelTree = false
          }else{
            self.isNeedAreaTree = true
            self.isNeedChannelTree = true
          }
          if(params['parkSysType']==1){ //智泊云停车场
            // 加载该停车场全部区域的通道数据
            self.getAreaChannelData(obj)
            // 加载停车场区域数据
            self.getAreaData(obj)
          }
          window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
        }else{
          self.isNeedAreaTree = true
          self.isNeedChannelTree = true
          window.localStorage.removeItem(self.curPagePath)
          this.reloadAreaTree = !this.reloadAreaTree
          this.reloadChannelTree = !this.reloadChannelTree
        }
      }
    },
    // 选择区域
    setSelectedAreaNode(params){
      let self = this
      if(params){
        let searchObj = {}
        searchObj[this.paramNameForAreaTree] = params[this.paramNameForAreaTree]
        this.otherParams = $.extend({}, this.otherParams, searchObj);
        let curPageCache = window.localStorage.getItem(self.curPagePath)
        let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
        _curPageCache.areaIds = params[this.paramNameForAreaTree]
        _curPageCache.areaNames = params['areaNames']
        window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
        this.reloadChannelTree = !this.reloadChannelTree
      }
    },
    // 选择通道-全部通道
    setSelectedChannelNode(channelArr){
      let self = this
      let searchObj = {}
      let enterChannelNames = [] //进场通道
      let leaveChannelNames = [] //离场通道
      let channelNames = [] //所选通道名称集合
      let channelIds = [] //通道id
      let channelPids = [] //通道所属区域id
      if(Array.isArray(channelArr)){
        for(let i = 0; i<channelArr.length; i++){
          let itemObj = channelArr[i]
          if(itemObj.channelType==1){ //进口
            enterChannelNames.push(itemObj.channelName)
          }else if(itemObj.channelType==2){ //出场
            leaveChannelNames.push(itemObj.channelName)
          }
          channelNames.push(itemObj.channelName)
          channelIds.push(itemObj.channelId)
          channelPids.push(itemObj.pid)
        }
        if(enterChannelNames.length > 1){
          searchObj['enterChannelNames'] = enterChannelNames.join(',')
          delete this.otherParams['enterChannelName']
        }else{
          searchObj['enterChannelName'] = enterChannelNames.length ? enterChannelNames.join(',') : ''
          delete this.otherParams['enterChannelNames']
        }

        if(leaveChannelNames.length > 1){
          searchObj['leaveChannelNames'] = leaveChannelNames.join(',')
          delete this.otherParams['leaveChannelName']
        }else{
          searchObj['leaveChannelName'] = leaveChannelNames.length ? leaveChannelNames.join(',') : ''
          delete this.otherParams['leaveChannelNames']
        }
        this.otherParams = $.extend({}, this.otherParams, searchObj);
        let curPageCache = window.localStorage.getItem(self.curPagePath)
        let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
        _curPageCache.channelNames = channelNames.join(',')
        _curPageCache.channelIds = channelIds.join(',')
        _curPageCache.channelPids = channelPids.join(',')
        _curPageCache.enterChannelNames = enterChannelNames.join(',') || ''
        _curPageCache.leaveChannelNames = leaveChannelNames.join(',') || ''
        window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
      }
    },
    // 选择通道-进场通道
    setSelectedChannelNode2(channelArr){
      let self = this
      let searchObj = {}
      let enterChannelNames = [] //进场通道
      let leaveChannelNames = [] //离场通道
      let channelNames = [] //所选通道名称集合
      let channelIds = [] //通道id
      let channelPids = [] //通道所属区域id
      if(Array.isArray(channelArr)){
        for(let i = 0; i<channelArr.length; i++){
          let itemObj = channelArr[i]
          if(itemObj.channelType==1){ //进口
            enterChannelNames.push(itemObj.channelName)
          }else if(itemObj.channelType==2){ //出场
            leaveChannelNames.push(itemObj.channelName)
          }
          channelNames.push(itemObj.channelName)
          channelIds.push(itemObj.channelId)
          channelPids.push(itemObj.pid)
        }
        if(enterChannelNames.length > 1){
          searchObj['enterChannelNames'] = enterChannelNames.join(',')
          delete this.otherParams['enterChannelName']
        }else{
          searchObj['enterChannelName'] = enterChannelNames.length ? enterChannelNames.join(',') : ''
          delete this.otherParams['enterChannelNames']
        }

        if(leaveChannelNames.length > 1){
          searchObj['leaveChannelNames'] = leaveChannelNames.join(',')
          delete this.otherParams['leaveChannelName']
        }else{
          searchObj['leaveChannelName'] = leaveChannelNames.length ? leaveChannelNames.join(',') : ''
          delete this.otherParams['leaveChannelNames']
        }
        this.otherParams = $.extend({}, this.otherParams, searchObj);
        let curPageCache = window.localStorage.getItem(self.curPagePath)
        let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
        _curPageCache.channelNames = channelNames.join(',')
        _curPageCache.channelIds = channelIds.join(',')
        _curPageCache.channelPids = channelPids.join(',')
        _curPageCache.enterChannelNames = enterChannelNames.join(',') || ''
        _curPageCache.leaveChannelNames = leaveChannelNames.join(',') || ''
        window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
      }
    },
    // 获取停车场区域数据
    getAreaData(obj){
      let self = this
      // 加载停车场区域数据
      API.fetchGet('commonFun/park/findParksAreaTree.do',obj).then(res=>{
        if(res.data){
          let areaTreeData = res.data
          if(Array.isArray(areaTreeData) && areaTreeData.length){
            for(let i = 0; i<areaTreeData.length; i++){
              let _data = JSON.stringify(areaTreeData[i])
              _data = _data.replace(/(\"open\"\:true\,)/g, '"open": false,');
              areaTreeData[i] = JSON.parse(_data);
            }
            let curPageCache = window.localStorage.getItem(self.curPagePath)
            let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
            _curPageCache.areaTreeData = JSON.stringify(areaTreeData) 
            window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
            this.reloadAreaTree = !this.reloadAreaTree
          }
        }
      },err=>{})
    },
    // 更新对应停车场的区域数据
    updateParkingLotAreaData(parkId){
      let self = this
      if(!parkId){
        return
      }
      API.fetchGet('commonFun/park/findParkAreaTree.do',{parkId:parkId}).then(res=>{
        if(res.data){
          let _data = JSON.stringify(res.data[0])
          _data = JSON.parse(_data);
          let curPageCache = window.localStorage.getItem(self.curPagePath)
          let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
          let areaTreeData = _curPageCache.areaTreeData ? JSON.parse(_curPageCache.areaTreeData) : []
          for(let i = 0; i<areaTreeData.length; i++){
            if(areaTreeData[i].parkId==parkId){
              areaTreeData[i] = _data
              _curPageCache.areaTreeData = JSON.stringify(areaTreeData)
              window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
              self.reloadAreaTree = !self.reloadAreaTree
              break;
            }
          }
        }
      },err=>{})
    },
    // 更新对应停车场的通道数据
    updateParkingLotChannelData(parkId,url){
      let self = this
      if(!parkId){
        return
      }
      API.fetchGet(url,{parkId:parkId}).then(response=>{
        if(response.data){
          let rootAreaChannelData = response.data[0] //停车场对象
          if(!rootAreaChannelData.children){
            return
          }
          let childAreaChannelData = []
          let rootAreaChildChannelObj = rootAreaChannelData.children[0] //根区域
          let rootAreaChildChannelData = rootAreaChildChannelObj.children ? rootAreaChildChannelObj.children : []
          for(let i = rootAreaChildChannelData.length-1; i>=0; i--){
            let itemObj = rootAreaChildChannelData[i];
            if(itemObj.children){
              itemObj.isHidden = true
              childAreaChannelData.push(itemObj) //把根区域里面的子区域拿出来
              rootAreaChildChannelData.splice(i,1) //删除子区域
            }
          }
          rootAreaChildChannelObj.isHidden = false
          let arr1 = rootAreaChannelData.children
          arr1.push.apply(arr1,childAreaChannelData);
          let curPageCache = window.localStorage.getItem(self.curPagePath)
          let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
          let channelTreeData = _curPageCache.channelTreeData ? JSON.parse(_curPageCache.channelTreeData) : []
          for(let i = 0; i<channelTreeData.length; i++){
            if(channelTreeData[i].parkId==parkId){
              channelTreeData[i] = rootAreaChannelData
              _curPageCache.channelTreeData = JSON.stringify(channelTreeData)
              window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
              self.reloadChannelTree = !self.reloadChannelTree
              break;
            }
          }
        }
      },err=>{})
    },
    // 获取子区域通道数据
    getAreaChannelData(obj){
      let self = this
      API.fetchGet('commonFun/park/findParksEnterChannelTree.do',obj).then(response=>{
        if(response.data){
          let parkNodes = response.data
          for(let j = 0; j<parkNodes.length; j++){
            let rootAreaChannelData = parkNodes[j] //停车场对象
            let childAreaChannelData = []
            let rootAreaChildChannelObj = rootAreaChannelData.children[0] //根区域
            let rootAreaChildChannelData = rootAreaChildChannelObj.children ? rootAreaChildChannelObj.children : []
            for(let i = rootAreaChildChannelData.length-1; i>=0; i--){
              let itemObj = rootAreaChildChannelData[i];
              if(itemObj.children){
                itemObj.isHidden = true
                childAreaChannelData.push(itemObj) //把根区域里面的子区域拿出来
                rootAreaChildChannelData.splice(i,1) //删除子区域
              }
            }
            rootAreaChildChannelObj.isHidden = false
            let arr1 = rootAreaChannelData.children
            arr1.push.apply(arr1,childAreaChannelData);
            parkNodes[j].children = deepCopyObjArray(arr1)
          }
          let curPageCache = window.localStorage.getItem(self.curPagePath)
          let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
          _curPageCache.channelTreeData = JSON.stringify(parkNodes)
          window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
          this.reloadChannelTree = !this.reloadChannelTree
        }
      },err=>{})
    },
    // 获取区域通道所有数据
    getAreaAllChannelData(obj){
      let self = this
      API.fetchGet('commonFun/park/findParksChannelTree.do',obj).then(response=>{
        if(response.data){
          let parkNodes = response.data //停车场
          for(let j = 0; j<parkNodes.length; j++){
            let rootAreaChannelData = parkNodes[j] //停车场对象
            let childAreaChannelData = []
            let rootAreaChildChannelObj = rootAreaChannelData.children[0] //根区域
            let rootAreaChildChannelData = rootAreaChildChannelObj.children ? rootAreaChildChannelObj.children : []
            for(let i = rootAreaChildChannelData.length-1; i>=0; i--){
              let itemObj = rootAreaChildChannelData[i];
              if(itemObj.children){
                itemObj.isHidden = true
                childAreaChannelData.push(itemObj) //把根区域里面的子区域拿出来
                rootAreaChildChannelData.splice(i,1) //删除子区域
              }
            }
            rootAreaChildChannelObj.isHidden = false
            let arr1 = rootAreaChannelData.children
            arr1.push.apply(arr1,childAreaChannelData);
            rootAreaChannelData.children = deepCopyObjArray(arr1) 
          }
          let curPageCache = window.localStorage.getItem(self.curPagePath)
          let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
          _curPageCache.channelTreeData = JSON.stringify(parkNodes) 
          window.localStorage.setItem(self.curPagePath,JSON.stringify(_curPageCache))
          this.reloadChannelTree = !this.reloadChannelTree
        }
      },err=>{})
    },
    // 获取根区域的通道数据
    getRootAreaChannelData(obj){
      let self = this
      // 获取停车场的根区域的通道
      API.fetchGet('commonFun/park/findParkRootEnterChannelTree.do',obj).then(res=>{
        if(res.data){
          let rootAreaChannelData = res.data[0]
          self.channelTreeData.push(rootAreaChannelData)
        }
      },err=>{})
    },
    disabledDate(time) {
      return time.getTime() >= new Date().getTime(); //今天日期可以选
      // return time.getTime() > Date.now() - 8.64e7; //今天日期不可选
    },
    // 搜索栏-时间维度更改
    handleSearchChange(item) {
      if(item.text=='时间维度'){
        this.changeReportDimension(item);
      }
    },
    changeReportDimension(item) {
      let value = item.value,
        ThisSearchItem = this.searchList[1];
      var today = [new Date(moment().subtract(1,'days').format("YYYY-MM-DD 00:00:00")), new Date(moment().subtract(1,'days').format("YYYY-MM-DD 23:59:59"))]; //昨天
      var month = new Date(
        moment()
          .subtract(1,'month')
          .format('YYYY-MM')
      ); //前一个月
      var year = new Date(moment().format('YYYY')); //当前年份
      switch (value) {
        case 'day':
        case 'custom':
        case 'DATE':
        case 'CUSTOM':
          ThisSearchItem.style = {
            width: '360px'
          };
          ThisSearchItem.flag = 'daterange';
          ThisSearchItem.pickerType = 'daterange';
          ThisSearchItem.format = 'yyyy-MM-dd';
          ThisSearchItem.value = today;
          break;
        case 'month':
        case 'MONTH':
          ThisSearchItem.style = {
            width: '185px'
          };
          ThisSearchItem.flag = 'month';
          ThisSearchItem.pickerType = 'month';
          ThisSearchItem.format = 'yyyy-MM';
          ThisSearchItem.value = month;
          break;
        case 'year':
        case 'YEAR':
          ThisSearchItem.style = {
            width: '125px'
          };
          ThisSearchItem.flag = 'year';
          ThisSearchItem.pickerType = 'year';
          ThisSearchItem.format = 'yyyy';
          ThisSearchItem.value = year;
          break;
      }
    },
  }
}
